'use strict'
app.controller('CodeFormController', function($scope, $http, $timeout, time, obj, $stateParams) {

	$scope.api = $scope.serverUrl + "web/template";

    let id = $stateParams.id;
    // console.log(id)

    $scope.id = id;
    
    $scope.query = {
        "size": 10,
        "page": 1,
        "name": ""
    };
    
    $scope.form = {
        "parent": 'com.cs',
        "author": 'wind',
        "datasourceId": '',
        "tables": [],
        "templates": [],
        "projectId": id
    };

    $scope.nameTypeArr = [
        {id: 0, name: '默认'},
        {id: 1, name: '小驼峰'},
        {id: 2, name: '大驼峰'}
    ];

    $scope.typeArr = [
        {id: 0, name: '公共'},
        {id: 1, name: '私有'},
    ]

    $scope.tplTypeArr = [
        {id: "freemarker", name: 'freemarker'},
        {id: "velocity", name: 'velocity'},
    ]

    $scope.fileTypeArr = [];

    $scope.dialog = {
        "isAdd": true,
        "title": "新增",
    };

    $scope.body = {
        "queryTitle": "查询条件",
        "tableTitle": "数据列表"
    };

    $scope.returnData = {
        recordsTotal: 0,
        recordsFiltered: 0,
        data: []
    };


    $scope.datasourceArr = [];

    $scope.tableArr = [];

    $scope.templateArr = [];

    let layer = layui.layer;


    $timeout(function(){
        if(id == 0){
            $http.post($scope.serverUrl + 'web/datasource/list', {type: 0}).then(function(res){
                // console.log(response);
                if(res.data.code === 1){
                    $scope.datasourceArr = res.data.data;
                }
            }, function(err){

            });
            $http.post($scope.serverUrl + 'web/template/list', {type: 0}).then(function(res){
                // console.log(response);
                if(res.data.code === 1){
                    $scope.templateArr = res.data.data;
                    // console.log($scope.templateArr);
                    for(let i = 0; i < $scope.templateArr.length; i++){
                        $('#template').append('<option value="' + $scope.templateArr[i].id + '">'+ $scope.templateArr[i].name + '</option>');
                    }
                    $('#template').trigger('chosen:updated');
                }
            }, function(err){

            });
        }else{
            $http.post($scope.serverUrl + 'web/projectToDatasource/list', {projectId: id}).then(function(res){
                // console.log(response);
                if(res.data.code === 1){
                    $scope.datasourceArr = res.data.data;
                }
            }, function(err){

            });
            $http.post($scope.serverUrl + 'web/projectToTemplate/list', {projectId: id}).then(function(res){
                // console.log(response);
                if(res.data.code === 1){
                    $scope.templateArr = res.data.data;
                    // console.log($scope.templateArr);
                    for(let i = 0; i < $scope.templateArr.length; i++){
                        $('#template2').append('<option value="' + $scope.templateArr[i].id + '">'+ $scope.templateArr[i].name + '</option>');
                    }
                    $('#template2').trigger('chosen:updated');
                }
            }, function(err){

            });
        }
    }, 0);


    $scope.selectDatasource = function(){
        // console.log($scope.form.datasourceId)
        $http.post($scope.serverUrl + 'web/datasource/tables', {id: $scope.form.datasourceId}).then(function(res){
            // console.log(response);
            if(res.data.code === 1){
                $scope.tableArr = res.data.data;
                for(let i = 0; i < $scope.tableArr.length; i++){
                    $('#table').append('<option value="' + $scope.tableArr[i].name + '">'+ $scope.tableArr[i].name + '</option>');
                }
                $('#table').trigger('chosen:updated');
            }
        }, function(err){

        });
    };

    $scope.save = function (){
        $http({
            method : 'POST',
            url : $scope.serverUrl + "web/code/gen",
            data : $scope.form,
            headers : {
                'Content-type' : 'application/json;charset=UTF-8'
            },
            responseType: 'arraybuffer',
            transformRequest : function(obj) {
                return JSON.stringify(obj);
            }
        }).then(function (data) {
            const decoder = new TextDecoder('utf-8');
            const text = decoder.decode(data.data);
            // console.log(text)
            if(text.indexOf("code") > -1 && text.indexOf("500") > -1){
                const json = JSON.parse(text);
                layer.msg(json.msg, {icon: 5});
                return;
            }
            //type对应着所需要下载的文件类型
            let blob = new Blob([data.data], {type: "application/octet-stream"});
            let objectUrl = URL.createObjectURL(blob);

            let a = document.createElement('a');
            document.body.appendChild(a);
            a.setAttribute('style', 'display:none');
            a.setAttribute('href', objectUrl);
            //下载的文件名称
            let filename= "code.zip";
            a.setAttribute('download', filename);
	        a.click();
	        URL.revokeObjectURL(objectUrl);
            document.body.removeChild(a)

            // window.open(objectUrl);
	    }, function (err) {

	    });
    }
});